﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Collections;
using Net.Sz.Framework.Szlog;



/// <summary>
/// 异步网络底层
/// zhangwei
/// </summary>
/// 
public enum NetState
{
    CONNECT = 1,
    SEND,
    RECV,
    CLOSE
}

public class CAsynNet
{
    private static SzLogger log = SzLogger.getLogger();

    private Socket mclientsocket = null;                                                    //socket 句柄
    private bool misconnect = false;                                                        //是否与服务器连接

    private SocketError mrecverror;                                                         //socket错误信息

    internal byte[] Buffers;
    private static Queue mqueue = Queue.Synchronized(new Queue());                          //接收消息队列
    private int msendseq = 1;
    private bool missend = false;                                                           //是否发送
    private static Random mrandom = new Random();

    public void ConnectServer(string ip, int port)
    {
        if (misconnect == true)
        {
            return;
        }
        msendseq = mrandom.Next(1, 10001);
        StartConnect(ip, port);
    }

    public void CloseConnect()
    {
        try
        {
            misconnect = false;
            missend = false;
            mclientsocket.Shutdown(SocketShutdown.Both);
            mclientsocket.Disconnect(true);
            mclientsocket.Close();
        }
        catch (Exception e)
        {
            log.Error(e.StackTrace);
        }
    }

    public bool IsConnect()
    {
        return misconnect;
    }

    public bool IsEmpty()
    {
        return mqueue.Count == 0;
    }


    public void StartConnect(string ip, int port)
    {
        IPAddress ipaddress = IPAddress.Parse(ip);
        IPEndPoint remoteep = new IPEndPoint(ipaddress, port);
        mclientsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        mclientsocket.NoDelay = true;
        mclientsocket.LingerState.Enabled = true;
        mclientsocket.LingerState.LingerTime = 5;

        SocketAsyncEventArgs eventArgs = new SocketAsyncEventArgs();
        eventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(SocketConnectCompeleted);
        eventArgs.RemoteEndPoint = remoteep;

        try
        {
            this.mclientsocket.ConnectAsync(eventArgs);
        }
        catch (Exception e)
        {
            log.Error("网络底层出现错误:" + e.StackTrace);
        }
    }

    public void SocketConnectCompeleted(object sender, SocketAsyncEventArgs args)
    {
        if (args.SocketError == SocketError.Success)
        {
            //DDebug.LogError("连接成功");
            misconnect = true;
            Buffers = new byte[4096];
            this.ProcessReceive(0, 6);
        }
    }


    public void Send(short msgid, byte[] msg)
    {

    }

    private void SendComplete(object sender, SocketAsyncEventArgs args)
    {
        if (args.SocketError != SocketError.Success)
        {
            log.Error("发送消息出现错误=>" + args.SocketError);
        }
    }

    private void ProcessReceive(int startpos, int size)
    {
        try
        {
            if (mclientsocket == null || !misconnect)
            {
                log.Error("----------------网络没有连接-------------------");
                return;
            }
            mrecverror = SocketError.Success;
            mclientsocket.BeginReceive(Buffers, 0, Buffers.Length, SocketFlags.None, out mrecverror, new AsyncCallback(ReceiveCallback), this);
        }
        catch (Exception e)
        {
            log.Error("网络底层出现错误:" + e.StackTrace);
        }
    }

    private void ReceiveCallback(IAsyncResult ar)
    {
        try
        {
            int datalength = 0;
            try
            {
                datalength = this.mclientsocket.EndReceive(ar);
            }
            catch (Exception e)
            {
                datalength = 0;
            }
            log.Error("客户端收到来自服务器的消息："+datalength);
            this.ProcessReceive(0, 6);
        }
        catch (Exception e)
        {
            log.Error(e.StackTrace);
        }
    }

}
